package tech.autumn.exception.resolver;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import tech.autumn.spec.web.Response;

/**
 * 异常解析器
 * @author koko
 * @date 2025年01月21日 14:35
 */
public abstract class AbstractHandlerExceptionJsonResolver implements HandlerExceptionResolver {

    protected MappingJackson2JsonView jsonView = new MappingJackson2JsonView();

    public MappingJackson2JsonView getJsonView() {
        return jsonView;
    }

    public void setJsonView(MappingJackson2JsonView jsonView) {
        this.jsonView = jsonView;
    }

    /**
     * 请求失败
     *
     * @param status HTTP返回码
     * @param msg    失败提示信息
     * @return JSON（ModelAndView）
     */
    protected ModelAndView fail(HttpStatus status, String msg) {
        ModelAndView mav = new ModelAndView(jsonView, Response.fail(status.value()).msg(msg));
        mav.setStatus(status);
        return mav;
    }

    /**
     * 业务失败(请求处理成功)
     *
     * @param code 业务返回码
     * @param msg  业务提示信息
     * @return JSON（ModelAndView）
     */
    protected ModelAndView businessFail(String code, String msg) {
        return new ModelAndView(jsonView, Response.fail(code).msg(msg));
    }

}
